import TChip from 't/basic/chip/Component.vue';

import useMappingProps from 't/common/hooks/useMappingProps';
import {
  commonProps,
  pickOwnForBasicComponent,
  usePropsTwoWayValues,
} from 't/common/utils';
import {
  computed,
  defineComponent,
  getCurrentInstance,
  nextTick,
  onMounted,
  reactive,
  ref,
  toRef,
  watch,
} from 'vue';

import './ChipGroup.scss';
import _, { forIn } from 'lodash';

import {
  date,
  debounce,
  dom,
  setCssVar,
  useQuasar,
  scroll,
} from '@teld/q-components';

import {
  useClipProps,
  useClipItem,
} from 't/bussiness/quick-filter/use-quick-filter';

import TSelectHelper from 't/bussiness/select-helper';
import HelpTip from './HelpTip';

export default defineComponent({
  props: {
    ...commonProps,
    ...useClipProps,
    showAllItem: { type: Boolean, default: true },

    searchCallBack: {
      type: Function,
      default() {
        return async (
          selectHelperPageIndex,
          selectHelperPageSize,
          defaultInputFilter,
          advanceFilter,
          dynamicFilter,
        ) => {};
      },
    },
    filter_dataValue: {
      type: String,
      default() {
        return '';
      },
    },
    placeholder: {
      type: String,
      default: '',
    },
    // labelField: {
    //   type: String,
    //   default() {
    //     return 'FullName';
    //   },
    // },
    // valueField: {
    //   type: String,
    //   default() {
    //     return 'Code';
    //   },
    // },
    // displayMapping: {
    //   type: String,
    //   default() {
    //     return 'quickFilter.Name';
    //   },
    // },
    // valueMapping: {
    //   type: String,
    //   default() {
    //     return 'quickFilter.Value';
    //   },
    // },
  },
  emits: ['filterChanged'],

  setup(props, { attrs, emit, expose, slots }) {
    const vm = getCurrentInstance();
    const $q = useQuasar();

    function emitFilterChanged() {
      emit('filterChanged');
    }

    const { computedClips } = useClipItem(props);

    const computedDataSource = computed(() => {
      let returnValue = JSON.parse(props.filter_dataValue);
      return returnValue;
    });

    watch(
      () => props.clips,
      clips => {
        singleText.value = clips[0]?.label;
      },
    );

    let { labelField = 'Name', valueField = 'Code' } = computedDataSource.value;

    let modelValue = computed({
      get: () => {
        let returnValue = _.transform(
          props.clips,
          (result, item) => {
            if (item.selected) {
              result.push({
                [labelField]: item.label,
                [valueField]: item.value,
              });
            }
          },
          [],
        );
        // let s = returnValue?.[0]?.[labelField];
        return props.isMultiple ? returnValue : returnValue?.[0]?.[valueField];
      },
      set: newValue => {
        if (props.isMultiple) {
          let newRangeVlaue = newValue.map(o => ({
            selected: true,
            label: o[labelField],
            value: o[valueField],
          }));
          if (0 === newRangeVlaue.length) {
            /** 防止没有值组件不显示 */
            newRangeVlaue.push({
              selected: false,
            });
          }
          singleText.value = newValue?.[0]?.[valueField];
          emit('update:clips', newRangeVlaue);
        } else {
          singleValue.value = newValue;
        }
      },
    });

    function emitClipsWithSingle() {
      if (false === props.isMultiple) {
        if (_.isEmpty(singleText.value) && _.isEmpty(singleValue.value)) {
          /** 当 值 和 显示 都没有时，防止没有值组件不显示 */
          emit('update:clips', [{ selected: false }]);
        } else {
          emit('update:clips', [
            {
              selected: true,
              label: singleText.value,
              value: singleValue.value,
            },
          ]);
        }
      }
    }

    let singleText = ref();
    let singleValue = ref();

    function getRandomInt(min, max) {
      min = Math.ceil(min);
      max = Math.floor(max);
      return Math.floor(Math.random() * (max - min)) + min;
    }
    const selectHelperIC = ref(`selectHelperID_${getRandomInt(1, 10000)}`);
    // const selectHelperIC = Symbol('selectHelperID');

    const selectedCount = computed(() => {
      return props.clips.filter(f => f.selected).length;
    });

    const render = () => {
      return (
        <div class='row FilterItem items-center SelectHelper'>
          {slots.before && slots.before()}
          {props.showTitle && props.label && (
            <div class='t-quick-filter_chip-group-label'>
              {props.label}
              <HelpTip {...props}></HelpTip>
            </div>
          )}
          <div class={['SelectHelper-container']}>
            <TSelectHelper
              instanceCode={selectHelperIC.value}
              class={[
                't-quick-filter-select-helper',
                'tr-input-form',
                selectedCount.value > 1 &&
                  't-quick-filter-select-helper--fix-width',
              ]}
              searchEnable={true}
              searchPosition='top'
              icon='arrow'
              simple={true}
              dropDownWidthStatic='100%'
              historyEnable={false}
              placeholder={props.placeholder}
              // historySaveCount='3'
              // helperCode=''
              pagination={true}
              countPerPage='10'
              maxCountPerPage='10'
              multiple={props.isMultiple}
              showChecked={true}
              maxCheckedLength='10'
              isSingle={false}
              openType='bottom'
              height='80%'
              // listDataSource={
              //   {
              //   }
              // }
              columns={[]}
              // v-model:value={props.value}
              v-model:value={modelValue.value}
              text={singleText.value}
              onUpdate:text={newText => {
                singleText.value = newText;
                emitClipsWithSingle();
              }}
              onConfirm={emitFilterChanged}
              valueMapping={`.${valueField}`}
              displayMapping={`.${labelField}`}
              labelField={labelField}
              valueField={valueField}
              iconEnable={false}
              helpPlacement='bottom'
              readonly={false}
              labelPosition='top'
              tabIndex='1'
              hideLabel={true}
              // pageid='PageID'
              search={selectHelperSearchConfig}
            ></TSelectHelper>
          </div>
          {props.isLast && <span class={['divider']}></span>}
        </div>
      );
    };

    async function selectHelperSearchConfig(
      selectHelperPageIndex,
      selectHelperPageSize,
      defaultInputFilter,
      advanceFilter,
      dynamicFilter,
    ) {
      return props.searchCallBack(
        selectHelperPageIndex,
        selectHelperPageSize,
        defaultInputFilter,
        advanceFilter,
        dynamicFilter,
      );
    }

    return () => {
      return render();
    };
  },
});
